//https://leetcode.cn/problems/minesweeper/
class Solution {
    char[][] board;
    int[] dx = {0, 0, 1, -1, -1, -1, 1, 1};
    int[] dy = {1, -1, 0, 0, -1, 1, -1, 1};
    int m, n;
    public char[][] updateBoard(char[][] board_, int[] click) {
        board = board_;
        m = board.length;
        n = board[0].length;
        int sx = click[0], sy = click[1];
        char ch = board[sx][sy];
        if(ch == 'M') {
            board[sx][sy] = 'X';
            return board;
        }
        if(ch == 'B') return board;
        dfs(sx, sy);
        return board;
    }
    public void dfs(int i, int j) {
        int count = 0;
        for(int k = 0; k < 8; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'M') {
                count++;
            }
        }
        if(count != 0) {
            //周围有地雷
            board[i][j] = (char)(count + '0');
            return;
        }else {
            //周围没有地雷
            board[i][j] = 'B';
            for(int k = 0; k < 8; k++) {
                int x = i + dx[k], y = j + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'E') {
                    dfs(x, y);
                }
            }
        }
    }
}